package com.spice.service.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spice.common.constant.PermissionConstant;
import com.spice.common.exception.SpiceException;
import com.spice.common.result.Response;
import com.spice.common.result.ResultCodeEnum;
import com.spice.common.util.CheckUtil;
import com.spice.common.util.PermissionUtil;
import com.spice.service.entity.form.SaveBatchForm;
import com.spice.service.entity.pojo.Ingredient;
import com.spice.service.util.ShiroUtil;
import com.spice.service.entity.form.EditEntityForm;
import com.spice.service.entity.form.PageForm;
import com.spice.service.entity.pojo.PackMaintain;
import com.spice.service.service.PackMaintainService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/packMaintain")
public class PackMaintainController {
    @Autowired
    PackMaintainService packMaintainService;

    @ApiOperation("根据产品名称进行搜索")
    @PostMapping(value = "/getDataByProductName", produces = "application/json;charset=UTF-8")
    public Response getDataByProductName(@RequestBody EditEntityForm<PackMaintain> editEntityForm) {
        if (!ShiroUtil.checkPermission(
                PermissionUtil.combinePermission(
                        PermissionConstant.PACK_MAINTAIN,
                        PermissionConstant.VIEW_PERMISSION
                )
        )) {
            throw new SpiceException().message("没有搜索权限");
        }
        //需要查找的名称
        String productName = editEntityForm.getT().getProductName();
        if (CheckUtil.objectsHasNull(productName)) {
            return Response.setResult(ResultCodeEnum.PARAM_LACK);
        }
        List<PackMaintain> list = packMaintainService.list(new LambdaQueryWrapper<PackMaintain>().like(PackMaintain::getProductName, productName));
        if (list.size() == 0) {
            return Response.error().message("找不到对应的产品包装信息");
        }
        return Response.ok().data("targetData", list);
    }

    @ApiOperation("分页查询")
    @PostMapping(value = "getDataByPage", produces = "application/json;charset=UTF-8")
    public Response getDataByPage(@RequestBody PageForm<PackMaintain> pageForm) {
        if (!ShiroUtil.checkPermission(
                PermissionUtil.combinePermission(
                        PermissionConstant.PACK_MAINTAIN,
                        PermissionConstant.VIEW_PERMISSION
                )
        )) {
            throw new SpiceException().message("没有查看权限");
        }
        // 检测必要参数是否缺失
        if (CheckUtil.objectsHasNull(pageForm,
                pageForm.getCurrentPage(),
                pageForm.getSize())) {
            return Response.setResult(ResultCodeEnum.PARAM_LACK);
        } else {
            // 生成page
            Page<PackMaintain> page = packMaintainService.page(
                    new Page<>(pageForm.getCurrentPage(), pageForm.getSize()),
                    pageForm.getQueryWrapper());
            // 携带page信息并返回
            return Response.ok()
                    .data("records", page.getRecords())
                    .data("currentPage", page.getCurrent())
                    .data("size", page.getSize())
                    .data("totalPage", page.getTotal())
                    .data("hasNext", page.hasNext())
                    .data("hasPrevious", page.hasPrevious());
        }
    }

    @ApiOperation(value = "编辑表中的数据信息（save,remove,update）;",
            notes = "editEntityForm中必要参数:id,t;  \n"
                    + "save:必要参数:serialName,productName,updateReason,maintainer;同一系列中的产品名称不可重复;  \n"
                    + "update:修改后的产品名称不能与同系列已有的重复;  \n")
    @PostMapping(value = "/editPackMaintain/{method}", produces = "application/json;charset=UTF-8")
    public Response editPackMaintain(@PathVariable("method") String method,
                                     @RequestBody EditEntityForm<PackMaintain> editEntityForm) {
        //检查权限
        if (!ShiroUtil.checkPermission(
                PermissionUtil.combinePermission(
                        PermissionConstant.PACK_MAINTAIN,
                        PermissionConstant.EDIT_PERMISSION
                ))) {
            throw new SpiceException().message("没有编辑权限");
        }
        // 判断是否有method参数
        if (CheckUtil.objectsHasNull(method)) {
            return Response.setResult(ResultCodeEnum.PARAM_LACK);
        }
        //初始化对象
        PackMaintain newPackMaintain = editEntityForm.getT().cleanup();
        Long id = editEntityForm.getId();
        if ("save".equals(method)) {
            return packMaintainService.savePackMaintain(newPackMaintain);
        } else if ("remove".equals(method)) {
            return packMaintainService.removePackMaintain(id);
        } else if ("update".equals(method)) {
            return packMaintainService.updatePackMaintain(id, newPackMaintain);
        }
        return Response.ok().message("未执行任何操作");
    }

    @ApiOperation(value = "批量保存")
    @PostMapping(value = "/saveBatch", produces = "application/json;charset=UTF-8")
    public Response saveBatch(@RequestBody SaveBatchForm<PackMaintain> saveBatchForm) {
        for (PackMaintain object : saveBatchForm.getObjectList()) {
            editPackMaintain("save", new EditEntityForm<PackMaintain>(0L, object));
        }
        return Response.ok().message("批量导入成功");
    }
}
